package com.cicoding.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.cicoding.dao.ErrorProblemMapper;
import com.cicoding.dao.ProblemMapper;
import com.cicoding.dao.UserMapper;
import com.cicoding.request.GenerateRequest;
import com.cicoding.service.ProblemService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cicoding.bean.*;
import com.cicoding.config.properties.LinProperties;
import com.cicoding.service.DeptService;
import com.cicoding.service.RoleService;
import com.cicoding.utils.Userinfo;
import scala.Int;


@Controller
public class PageController extends BaseController {

	private Logger log = LoggerFactory.getLogger(this.getClass());


	@Autowired
	private DeptService deptService;
	@Autowired
	private LinProperties linProperties;
	@Autowired
	private RoleService roleService;
	@Autowired
	private ProblemService problemService;
	@Autowired
	private ErrorProblemMapper errorProblemMapper;
	@Autowired
	private ProblemMapper problemMapper;
	@Autowired
	private UserMapper userMapper;
	@RequestMapping(value = "/test", method = { RequestMethod.POST })
	public String test(HttpServletRequest request, HttpServletResponse response,@RequestBody Map<String,Object> answer) throws IOException {
		log.info("test page");
		Object o = answer.get("answer");
		System.out.println(o.toString());
		String s = o.toString();
		System.out.println("字符串"+s);
		String s1 = s.substring(1,s.length()-1);
		System.out.println(s1);
		String[] arr = s1.split(",");
		List<Integer> a = new ArrayList<>();
		int i =0;
		for (String s2 : arr) {
			if (i==0){
				a.add(Integer.parseInt(s2));
			}
			else {

				a.add(Integer.parseInt(s2.substring(1)));
			}
			i++;
			System.out.println(s2);

		}
		for (Integer integer : a) {
			System.out.println(integer);
		}
		System.out.println("接收到了");
		System.out.println(o);

		return "new";
	}
	@RequestMapping(value = "/new", method = { RequestMethod.GET })
	public String newpage(HttpServletRequest request){
		log.info("new page");
		System.out.println("做题完成");
		return "new";
	}
	@RequestMapping(value = "/test2", method = { RequestMethod.GET })
	public String test2(HttpServletRequest request, HttpServletResponse response) throws IOException {
		log.info("test2 page");
		
		
		
		return "test2";
	}

	@RequestMapping(value = "/login", method = { RequestMethod.GET })
	public String login(HttpServletRequest request) {
		request.setAttribute("kaptcha", linProperties.isKptchaswich());
		return "login2";
	}

	@RequestMapping(value = "/login2", method = { RequestMethod.GET })
	public String login2(HttpServletRequest request) {
		log.info("login page");
		request.setAttribute("kaptcha", linProperties.isKptchaswich());

		return "login2";
	}

	@RequestMapping(value = "/index1", method = { RequestMethod.GET })
	public String index1(HttpServletRequest request) {

		return "index1";
	}

	@RequestMapping(value = "/welcome", method = { RequestMethod.GET })
	public String welcome() {
		log.info("welcome page");
		return "welcome";
	}
	@RequestMapping(value = "/toRegisterPage", method = { RequestMethod.GET })
	public String register() {
		log.info("toRegisterPage");
		return "register";
	}
	@RequestMapping(value = "/userpage", method = { RequestMethod.GET })
	public String userpage(HttpServletRequest request) {
//		List<Dept> list = deptMapper.getAllDept();
		List<Dept> deptList = deptService.getAllDept();
		List<ShowRole> roleList = roleService.getAllShowRole();
		request.setAttribute("depts", deptList);
		request.setAttribute("roles", roleList);
		return "usergrid";
	}

	@RequestMapping(value = "/setpassword", method = { RequestMethod.GET })
	public String setPassword(HttpServletRequest request) {
		request.setAttribute("username", Userinfo.getUsername());
		request.setAttribute("sex", Userinfo.getSex());
		return "changepassword";
	}

	@RequestMapping(value = "/deptpage", method = { RequestMethod.GET })
	public String deptPage(HttpServletRequest request) {
		log.info("dept page");
		return "deptgrid";
	}

	@RequestMapping(value = "/menupage", method = { RequestMethod.GET })
	public String menuPage(HttpServletRequest request) {
		return "menugrid";
	}

	@RequestMapping(value = "/noticepage", method = { RequestMethod.GET })
	public String noticePage(HttpServletRequest request) {
		log.info("notice page");
		return "noticegrid";
	}

	@RequestMapping(value = "/introduction", method = { RequestMethod.GET })
	public String introduction(HttpServletRequest request) {
		log.info("introduction page");
		return "introduction";
	}

	@RequestMapping(value = "/loginlogpage", method = { RequestMethod.GET })
	public String loginLogPage(HttpServletRequest request) {
		log.info("login Log page");
		return "login_log_grid";
	}

	@RequestMapping(value = "/operationlogpage", method = { RequestMethod.GET })
	public String operationLogPage(HttpServletRequest request) {
		log.info("login Log page");
		return "operation_log_grid"; 
	}
	
	@RequestMapping(value = "/rolepage", method = { RequestMethod.GET })
	public String rolePage(HttpServletRequest request) {
		log.info("role page");
		return "rolegrid";
	}
	

	
	@RequestMapping(value = "/leavepage", method = { RequestMethod.GET })
	public String leavePage(HttpServletRequest request , Date start , Date end) {

		return "leavepage";
	}
	
	@RequestMapping(value = "/operationleavepage", method = { RequestMethod.GET })
	public String leaderLeavePage(HttpServletRequest request , Date start , Date end) {
		
		return "operationleavepage";
	}

	@RequestMapping(value = "/wrongpage", method = { RequestMethod.GET })
	public String wrongpage(HttpServletRequest request) {
		log.info("错题 page");
		int id = (int) request.getSession().getAttribute("id");
		System.out.println("获取到用户id为"+id);
		request.setAttribute("kaptcha", linProperties.isKptchaswich());
		List<ErrorProblem> errorProblemList = problemService.errorProblemList(id);
		request.setAttribute("errorProblemList",errorProblemList);
		return "wrong";
	}
	@RequestMapping(value = "/testpage", method = { RequestMethod.GET })
	public String testpage(HttpServletRequest request) {
		log.info("test page");
		request.setAttribute("kaptcha", linProperties.isKptchaswich());

		return "testpage2";
	}
	@RequestMapping(value = "/testpage1", method = { RequestMethod.POST })
	public String testpage1(HttpServletRequest request,String number1,String number2,String number3) {
		log.info("做题 page");
		if ("".equals(number2)){
			number2 = "0";
		}
		System.out.println("接收到参数number1"+number1);
		System.out.println("接收到参数number2"+number2);
		System.out.println("接收到参数number3"+number3);
		if (Integer.parseInt(number1)<Integer.parseInt(number2)){
			return "error_submit";
		}
		if (!"".equals(number3)&&(Integer.parseInt(number3)>6||Integer.parseInt(number3)<=0)){
			return "error_submit";
		}
		request.setAttribute("kaptcha", linProperties.isKptchaswich());
		GenerateRequest generateRequest = new GenerateRequest();
		if ("".equals(number3)){
			System.out.println("用户选择不挑战");
			generateRequest.setInputGrade((Integer) request.getSession().getAttribute("grade"));
		}
		else {
			System.out.println("用户选择挑战");
			generateRequest.setInputGrade(Integer.parseInt(number3));

		}
		generateRequest.setNum(Integer.parseInt(number1));
		if (Integer.parseInt(number2)==0){
			generateRequest.setBracketNum(0);
		}
		else {
			generateRequest.setBracketNum(Integer.parseInt(number2));
		}
		Set<String> problemTitle = problemService.generate(generateRequest);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
		List<Problem> problemList = new ArrayList<>();
		int counts = (int) request.getSession().getAttribute("counts");
		int id = (int) request.getSession().getAttribute("id");

		//更新用户的做题次数
		ShiroUser user = new ShiroUser();
		user.setUsername((String) request.getSession().getAttribute("username"));
		user.setId(id);
		user.setCounts(counts+1);
		user.setRoleid((Integer) request.getSession().getAttribute("roleid"));
		user.setSalt((String) request.getSession().getAttribute("salt"));
		user.setDeptid((Integer) request.getSession().getAttribute("deptid"));
		user.setPassword((String) request.getSession().getAttribute("password"));
		user.setGrade((Integer) request.getSession().getAttribute("grade"));
		user.setAvator((String) request.getSession().getAttribute("avator"));
		userMapper.updateById(user);
		int m = 1;
		for (String s : problemTitle) {
			Problem problem = new Problem();
			int result = problemService.calculate(s);
			problem.setTitle(s+"=");
			problem.setCounts(counts);
			problem.setCreateTime(date);
			problem.setUserId(id);
			problem.setRightAnswer(result);
			System.out.println("生成题目"+problem.getTitle());
			int a = problemMapper.insert(problem);
			System.out.println(a);
			problemList.add(problem);
		}
		for (Problem problem : problemList) {
			problem.setId(m);
			m++;
		}
		request.getSession().setAttribute("problemList",problemList);
		request.setAttribute("problemList",problemList);
		return "testpage1";
	}
	@RequestMapping(value = "/submitProblem", method = { RequestMethod.POST })
	public String submitProblem(HttpServletRequest request,@RequestBody Map<String,Object> answer) {
		log.info("提交做题");
		//拿到生成的题
		List<Problem> problemList = (List<Problem>) request.getSession().getAttribute("problemList");
		//处理数据
		Object o = answer.get("answer");
		String s = o.toString();
		System.out.println("用户提交答案字符串为"+s);
		String s1 = s.substring(1,s.length()-1);
		String[] arr = s1.split(",");
		List<Integer> a = new ArrayList<>();
		int i =0;
		for (String s2 : arr) {
			if (i==0){
				a.add(Integer.parseInt(s2));
			}
			else {

				a.add(Integer.parseInt(s2.substring(1)));
			}
			i++;
		}
		System.out.println("用户提交答案数组");
		for (Integer integer : a) {
			System.out.println(integer);
		}
		int ri = 0;
		int ei = 0;
		int sum = problemList.size();
		List<ProblemVo> problemVoList = new ArrayList<>();
		for (int i1 = 0; i1 < problemList.size(); i1++) {
			int t = a.get(i1);
			Problem problem = problemList.get(i1);
			if (t!=problem.getRightAnswer()){
				ei++;
				ProblemVo problemVo = new ProblemVo();
				problemVo.setAnswer(t);
				problemVo.setPanduan("错误");
				problemVo.setTitle(problem.getTitle());
				problemVo.setRightAnswer(problem.getRightAnswer());
				problemVoList.add(problemVo);
				ErrorProblem errorProblem = new ErrorProblem();
				errorProblem.setAnswer(t);
				errorProblem.setCounts(problem.getCounts());
				errorProblem.setCreateTime(problem.getCreateTime());
				errorProblem.setTitle(problem.getTitle());
				errorProblem.setRightAnswer(problem.getRightAnswer());
				errorProblem.setUserId(problem.getUserId());
				errorProblemMapper.insert(errorProblem);
			}
			else {
				ri++;
				ProblemVo problemVo = new ProblemVo();
				problemVo.setAnswer(t);
				problemVo.setPanduan("正确");
				problemVo.setTitle(problem.getTitle());
				problemVo.setRightAnswer(problem.getRightAnswer());
				problemVoList.add(problemVo);
			}
		}
		request.getSession().removeAttribute("problemVo");
		request.getSession().removeAttribute("ei");
		request.getSession().removeAttribute("ri");
		request.getSession().removeAttribute("sum");
		request.getSession().removeAttribute("result");

		Double result1 = (ri/(sum*1.0))*100;

		String test = String.format("%.2f", result1);
		String result = test+"%";
		request.getSession().setAttribute("problemVo",problemVoList);
		request.getSession().setAttribute("ei",ei);
		request.getSession().setAttribute("ri",ri);
		request.getSession().setAttribute("sum",sum);
		request.getSession().setAttribute("result",result);
		return "testpage1";
	}
	@RequestMapping(value = "/toSingleProblem", method = { RequestMethod.GET })
	public String toSingleProblem(HttpServletRequest request,HttpServletResponse response) {
		String creatTime = request.getParameter("creatTime");
		String title = request.getParameter("title");
		Integer id = (Integer) request.getSession().getAttribute("id");
//		EntityWrapper<ErrorProblem> wrapper = new EntityWrapper<>();
//		wrapper.eq("title",title);
//		wrapper.eq("create_time",creatTime);
//		wrapper.eq("user_id",id);
		ErrorProblem errorProblem1 = new ErrorProblem();
		errorProblem1.setUserId(id);
		errorProblem1.setTitle(title);
		errorProblem1.setCreateTime(creatTime);
		ErrorProblem errorProblem = errorProblemMapper.selectOne(errorProblem1);
		request.setAttribute("errorProblem",errorProblem);
		return "testpage3";
	}
	@RequestMapping(value = "/submitSingleProblem", method = { RequestMethod.POST })
	public String submitProblem(HttpServletRequest request,String answer) {
		Integer id = (Integer) request.getSession().getAttribute("id");
		String createTime = request.getParameter("createTime");
		String title = request.getParameter("title");
		System.out.println(answer);
		System.out.println(createTime);
		System.out.println(title);
		ErrorProblem errorProblem1 = new ErrorProblem();
		errorProblem1.setUserId(id);
		errorProblem1.setTitle(title);
		errorProblem1.setCreateTime(createTime);
		List<ProblemVo> problemVoList = new ArrayList<>();
		ErrorProblem errorProblem = errorProblemMapper.selectOne(errorProblem1);

		if (Integer.parseInt(answer) == errorProblem.getRightAnswer()){
			ProblemVo problemVo = new ProblemVo();
			problemVo.setAnswer(Integer.parseInt(answer));
			problemVo.setPanduan("正确");
			problemVo.setTitle(title);
			problemVo.setRightAnswer(errorProblem.getRightAnswer());
			problemVoList.add(problemVo);
			errorProblemMapper.deleteById(errorProblem.getId());
		}
		else {
			ProblemVo problemVo = new ProblemVo();
			problemVo.setAnswer(Integer.parseInt(answer));
			problemVo.setPanduan("错误");
			problemVo.setTitle(title);
			problemVo.setRightAnswer(errorProblem.getRightAnswer());
			problemVoList.add(problemVo);
		}

		request.getSession().removeAttribute("problemVo");
		request.getSession().setAttribute("problemVo",problemVoList);
		return "testpage4";
	}
}
